#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PA模块 v1版本 - 处理登录和页面访问
"""

import requests
import json
import time
import logging
from urllib.parse import urljoin
import warnings

# 忽略SSL验证警告
warnings.filterwarnings("ignore", category=requests.packages.urllib3.exceptions.InsecureRequestWarning)

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def login_v1(username=None, password=None):
    """
    登录函数 v1版本
    
    Args:
        username: 用户名（可选）
        password: 密码（可选）
    
    Returns:
        list: cookies列表，登录失败返回None
    """
    
    # 默认登录信息
    if not username:
        username = "18616720630"
    if not password:
        password = "123456"
    
    session = requests.Session()
    
    try:
        # 登录URL
        login_url = "https://www.znjiyi.com/a/Handle/Login_Process.aspx"
        
        # 登录数据
        login_data = {
            'username': username,
            'password': password,
            'rememberme': 'false'
        }
        
        # 请求头
        headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'X-Requested-With': 'XMLHttpRequest',
            'Referer': 'https://www.znjiyi.com/',
            'Origin': 'https://www.znjiyi.com'
        }
        
        # 发送登录请求
        logger.info("正在发送登录请求...")
        response = session.post(
            login_url,
            data=login_data,
            headers=headers,
            verify=False,
            timeout=30
        )
        
        logger.info(f"登录响应状态码: {response.status_code}")
        
        if response.status_code == 200:
            try:
                result = response.json()
                logger.info(f"登录响应内容: {json.dumps(result, ensure_ascii=False)}")
                
                if result.get('result'):
                    logger.info("登录成功")
                    
                    # 提取cookies
                    cookies = []
                    for cookie in session.cookies:
                        cookie_dict = {
                            'name': cookie.name,
                            'value': cookie.value,
                            'domain': cookie.domain,
                            'path': cookie.path
                        }
                        cookies.append(cookie_dict)
                        logger.info(f"获取到cookie: {cookie.name}")
                    
                    return cookies
                else:
                    logger.error(f"登录失败: {result.get('message', '未知错误')}")
                    return None
                    
            except json.JSONDecodeError:
                logger.error("登录响应不是有效的JSON格式")
                logger.error(f"响应内容: {response.text}")
                return None
        else:
            logger.error(f"登录请求失败，状态码: {response.status_code}")
            return None
            
    except Exception as e:
        logger.error(f"登录过程中发生错误: {str(e)}")
        return None

def get_html_content_v1(url, cookies=None, headers=None):
    """
    获取HTML内容 v1版本
    
    Args:
        url: 目标URL
        cookies: cookies列表
        headers: 请求头（可选）
    
    Returns:
        str: HTML内容，失败返回None
    """
    
    session = requests.Session()
    
    # 添加cookies
    if cookies:
        for cookie in cookies:
            session.cookies.set(
                cookie['name'],
                cookie['value'],
                domain=cookie.get('domain', ''),
                path=cookie.get('path', '/')
            )
    
    # 默认请求头
    default_headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'Accept-Encoding': 'gzip, deflate, br',
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1'
    }
    
    if headers:
        default_headers.update(headers)
    
    try:
        logger.info(f"正在访问: {url}")
        response = session.get(
            url,
            headers=default_headers,
            verify=False,
            timeout=30
        )
        
        logger.info(f"响应状态码: {response.status_code}")
        
        if response.status_code == 200:
            # 设置编码
            response.encoding = 'utf-8'
            return response.text
        else:
            logger.error(f"访问失败，状态码: {response.status_code}")
            return None
            
    except Exception as e:
        logger.error(f"访问页面时发生错误: {str(e)}")
        return None

def post_request_v1(url, data, cookies=None, headers=None):
    """
    发送POST请求 v1版本
    
    Args:
        url: 目标URL
        data: POST数据
        cookies: cookies列表
        headers: 请求头（可选）
    
    Returns:
        requests.Response: 响应对象，失败返回None
    """
    
    session = requests.Session()
    
    # 添加cookies
    if cookies:
        for cookie in cookies:
            session.cookies.set(
                cookie['name'],
                cookie['value'],
                domain=cookie.get('domain', ''),
                path=cookie.get('path', '/')
            )
    
    # 默认请求头
    default_headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'X-Requested-With': 'XMLHttpRequest',
        'Accept': 'text/html, */*; q=0.01',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
    }
    
    if headers:
        default_headers.update(headers)
    
    try:
        logger.info(f"正在发送POST请求到: {url}")
        
        # 参考test.py的方式处理数据编码
        if isinstance(data, dict):
            import urllib.parse
            data_string = urllib.parse.urlencode(data)
            data_bytes = data_string.encode('utf-8')
        elif isinstance(data, str):
            data_bytes = data.encode('utf-8')
        else:
            data_bytes = data
        
        response = session.post(
            url,
            headers=default_headers,
            data=data_bytes,
            verify=False,
            timeout=30
        )
        
        # 设置响应编码
        response.encoding = 'utf-8'
        
        logger.info(f"POST响应状态码: {response.status_code}")
        
        return response
        
    except Exception as e:
        logger.error(f"POST请求时发生错误: {str(e)}")
        return None

# 为了兼容性，提供别名
login = login_v1
get_html_content = get_html_content_v1
post_request = post_request_v1

if __name__ == "__main__":
    # 测试登录
    cookies = login_v1()
    if cookies:
        print("登录测试成功")
        print(f"获取到 {len(cookies)} 个cookies")
    else:
        print("登录测试失败")